﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Graphics;
using Afru;
using System.IO;
using System.Threading;

namespace Afru
{
    public class ScreenshotManager
    {
       /// <summary>
       /// Allows you to take screenshots. NOTE: most likely wont work on wp7/xbox
       /// Will silently fail if it doesnt work
       /// </summary>
        #region Variables

        private Texture2D Screenshot;
        private string ScreenshotPath;
        private int w, h;

        #endregion

        #region Constructor

        public ScreenshotManager()
        {
            try
            {
                ScreenshotPath = Directory.GetCurrentDirectory() + "\\screenshots\\";
                if (!Directory.Exists(ScreenshotPath))
                {
                    Directory.CreateDirectory(ScreenshotPath);
                }
            }
            catch
            {

            }
        }

        #endregion

        #region Class functions

        private void SaveScreenshot(object o)
        {
            try
            {
                Texture2D t = (Texture2D)(o);
                using (FileStream fs = new FileStream(ScreenshotPath + "screenshot_" + DateTime.Now.ToString("yyyyMMddmmss") + "_" + DateTime.Now.Millisecond.ToString() + ".jpg", FileMode.CreateNew))
                {
                    t.SaveAsJpeg(fs, t.Width, t.Height);
                    //t.Dispose();
                }
            }
            catch
            {

            }
        }

        public void TakeScreenshot(GraphicsDevice Device, RenderTarget2D RenderTarget)
        {
            try
            {
                w = Device.PresentationParameters.BackBufferWidth;
                h = Device.PresentationParameters.BackBufferHeight;

                Screenshot = (Texture2D)RenderTarget;

                //save on a new thread, prevent locking
                ParameterizedThreadStart pts = new ParameterizedThreadStart(SaveScreenshot);
                Thread t = new Thread(pts);
                t.Start(Screenshot);

            }
            catch
            {

            }
        }

        #endregion

    }
}
